﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

using WindowsLive.Writer.Api;
using WindowsLive.Writer.CoreServices.Diagnostics;

namespace AmazonBookLinker.Diagnostics
{
  public static class PluginTracer
  {
    static PluginTracer()
    {
      string pluginDirectoryPath = Path.GetTempPath() + "AmazonBookLinker";
      if ( !Directory.Exists( pluginDirectoryPath ) )
        Directory.CreateDirectory( pluginDirectoryPath );

      var stream = File.Create( pluginDirectoryPath + @"\AmazonBookLinkerTraceInfo.log" );
      var listener = new TextWriterTraceListener( stream );
      listener.TraceOutputOptions |= TraceOptions.Callstack | TraceOptions.DateTime | TraceOptions.Timestamp | TraceOptions.LogicalOperationStack;
      Trace.Listeners.Clear();
      Trace.Listeners.Add( listener );
    }


    public static void LogException( Exception ex, string context )
    {
      LogException( ex, context, null );
    }


    public static void LogException( Exception ex, string context, Dictionary<string, string> parameters )
    {
      if ( parameters != null )
      {
        context += "\r\n";

        foreach ( var parameter in parameters )
          context += parameter.Key + " = " + parameter.Value + "\r\n";
      }

      PluginDiagnostics.LogException( ex, context );
      Trace.Close();
    }


    public static void DisplayUnexpectedException( Exception ex )
    {
      UnexpectedErrorMessage.Show( ex );
    }
  }
}